import moment from "moment";
const commonUtil = {
  /**
   * 格式化日期时间函数
   *
   * @param date
   * @returns {String}
   */
  formatStringToDateTime: (date) => {
    if (date) {
      return commonUtil.formatDate(new Date(date), "YYYY-MM-DD HH:mm:ss");
    }
    return "";
  },

  /**
   * 格式化日期函数
   *
   * @param date
   * @returns {String}
   */
  formatStringToDate: (date) => {
    if (date) {
      return commonUtil.formatDate(new Date(date), "YYYY-MM-DD");
    }
    return "";
  },

  /**
   * 格式化日期函数
   *
   * @param date
   * @param formatString
   * @returns {String}
   */
  formatDate: (date = new Date(), formatString = "YYYY-MM-DD HH:mm") => {
    if (formatString) {
      return moment(date).format(formatString);
    }
    return "";
  },

  /**
   * 下载二进制文件
   * @param data
   * @param fileName
   */
  streamFileDownload(data, fileName) {
    if (!data) {
      return;
    }
    const url = window.URL.createObjectURL(new Blob([data],
      { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }));
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    link.remove();
  },

  /**
   * 从指定数组中生成指定位数随机数
   * @param arr 指定数组
   * @param n 指定位数
   * @returns {*}
   */
  sampleRandomNumber: (arr = [], n = 16) => {
    const tempNmb = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
    const tempStr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
      "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    const temp = arr.length > 0 ? arr : tempNmb.concat(tempStr);
    const tempLength = temp.length;
    const str = [];
    for (let i = 0; i < n; i++) {
      const s = Math.floor(Math.random() * tempLength - 1);
      str.push(temp[s]);
    }
    return str.join("");
  },
  networkError(context) { // 网络错误提示
    context.$message({
      type: "warning",
      message: "网络异常，请稍后重试!"
    });
  },
  /**
   * 根据指定key去除数组
   * @param {Array} arr 指定数组
   * @param {String} key 指定的key
   * @returns {Array} arr
   */
  duplicateRemoval(arr, key) {
    const obj = {};
    return arr.reduce((res, item) => {
      obj[item[key]] ? "" : obj[item[key]] = res.push(item);
      return res;
    }, []);
  }
};

export default commonUtil;
